import cp from "node:child_process";

import { fileURLToPath } from "node:url";
import { dirname, resolve } from "node:path";

// const __dirname = dirname(fileURLToPath(import.meta.url))

// 启动子进程
export function fork(script, params = [], options) {
  const child = cp.fork(script, params);

  return child;
}

export async function watchDog(
  script,
  params = process.argv.slice(2),
  restartDelay = 30 * 1000
) {
  const child = fork(script, params);

  child.on("exit", (code) => {
    console.log("code", code);
    // if (code === 0) return;

    // 自动重启
    console.log(`[watchDog] 运行异常，${restartDelay / 1000}秒后重新运行`);

    setTimeout(() => watchDog(script, params), restartDelay);
  });
}
